import cv2
from ultralytics import YOLO

# 加载YOLOv8模型
model = YOLO(r'C:\Users\30514\PycharmProjects\yolov8_driving\runs\detect\yolov8s\weights\best.pt')  # 请替换为适合人脸检测的模型路径

def detect_boxes_and_draw(image_path, output_path):
    # 读取输入图片
    frame = cv2.imread(image_path)

    # 使用YOLOv8模型进行检测
    results = model(frame)  # 对图像进行检测

    boxes_coordinates = []  # 存储检测框坐标

    # 遍历检测结果并绘制检测框
    for result in results:
        boxes = result.boxes  # 获取检测框信息
        for box in boxes:
            x1, y1, x2, y2 = map(int, box.xyxy[0])  # 获取检测框坐标
            boxes_coordinates.append((x1, y1, x2, y2))  # 存储坐标信息

            # 绘制矩形框
            cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)  # 绿色框表示检测到的物体

    # 保存处理后的图片
    cv2.imwrite(output_path, frame)
    print(f"处理后的图片已保存到: {output_path}")

    return boxes_coordinates

if __name__ == '__main__':
    image_path = r'C:\Users\30514\PycharmProjects\yolov8_driving\test_images\output.jpg'  # 输入图片的路径
    output_path = r'C:\Users\30514\PycharmProjects\yolov8_driving\test_images\output_with_boxes.jpg'  # 保存结果图片的路径
    boxes_coordinates = detect_boxes_and_draw(image_path, output_path)
    print(f"检测框坐标信息: {boxes_coordinates}")
    print("Model is running on device:", model.device)
